package com.yuandengta.yomall.auth.controller;

import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.auth.exception.AuthBizException;
import com.yuandengta.yomall.auth.service.RegisterService;
import com.yuandengta.yomall.auth.service.SmsService;
import com.yuandengta.yomall.auth.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 登录注册 {@link LoginController}
 */

@Controller
public class LoginController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RegisterService registerService;

    /**
     * 校验用户是否存在
     *
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping("/check/user/{username}")
    public R checkUser(@PathVariable("username") String username) {
        Integer code = registerService.checkUser(username);
        return R.ok().put("code", code);
    }

    /**
     * 检查手机号是否存在
     *
     * @param mobile
     * @return
     */
    @ResponseBody
    @GetMapping("/check/mobile/{mobile}")
    public R checkMobile(@PathVariable("mobile") String mobile) {
        Integer code = registerService.checkMobile(mobile);
        return R.ok().put("code", code);
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("mobile") String mobile) {
        try {
            smsService.sendCode(mobile);
        } catch (AuthBizException e) {
            return R.error(e.getCode(), e.getMessage());
        }

        return R.ok();
    }

    /**
     * 用户注册
     *
     * @param registerVO
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/reg")
    public String register(@Valid UserRegisterVO registerVO, BindingResult result,
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            // 收集校验错误消息
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，重定向到注册页面
            // TODO 重定向携带数据, 利用Session原理. 到了目标页面从session中取出数据, 然后删除session中的数据.
            // TODO 分布式 Session 问题
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 校验验证码, 考虑验证码是否过期
        boolean b = smsService.checkCode(registerVO.getMobile(), registerVO.getCode());
        if (!b) {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 注册
        Map<String, String> errors = registerService.reg(registerVO);
        if (errors != null) {
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 注册成功，重定向到登录页
        return "redirect:http://auth.yomall.com/login.html";
    }

}
